package juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//一个初始值为0的变量，多个线程交替进行操作，一个加1，一个减1，值始终保持在 0 和 1之间切换
class ShareData{//资源类
    private int num = 0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void add() throws InterruptedException {
        lock.lock();
        try {
            while (num != 0){
                //不满足条件，进入等待
                condition.await();
            }
            //满足条件，可以干活
            num = num + 1;
            System.out.println("当前线程: "+Thread.currentThread().getName()+" 当前num: "+num);
            //干完活，通知别人
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }
    public void sub() throws InterruptedException {
        lock.lock();
        try {
            while (num == 0){
                //不满足条件，进入等待
                condition.await();
            }
            //满足条件，可以干活
            num = num - 1;
            System.out.println("当前线程: "+Thread.currentThread().getName()+" 当前num: "+num);
            //干完活，通知别人
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }
}

public class ProductorAndConsumer1 {

    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        new Thread(()->{
            for (int i=0;i<=3;i++){
                try {shareData.add();} catch (InterruptedException e) { e.printStackTrace();}
            }
        },"A线程").start();

        new Thread(()->{
            for (int i=0;i<=3;i++){
                try {shareData.add();} catch (InterruptedException e) { e.printStackTrace();}
            }
        },"B线程").start();

        new Thread(()->{
            for (int i=0;i<=3;i++){
                try {shareData.sub();} catch (InterruptedException e) { e.printStackTrace();}
            }
        },"C线程").start();

        new Thread(()->{
            for (int i=0;i<=3;i++){
                try {shareData.sub();} catch (InterruptedException e) { e.printStackTrace();}
            }
        },"D线程").start();
    }
}

